from typing import Any, List, Optional
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from datetime import datetime
import time

from app.api import deps
from app.schemas import airticket_order as schemas
from app.database.models.erp import AirticketOrder, CustomerProfile, PackageOrder
from app.database.models.base import User

router = APIRouter()

def generate_order_number() -> str:
    """生成订单号：年月日时分秒+3位随机数"""
    timestamp = datetime.now().strftime('%Y%m%d%H%M%S')
    random_num = str(int(time.time() * 1000))[-3:]
    return f"AIR{timestamp}{random_num}"

@router.get("/", response_model=List[schemas.AirticketOrder])
def list_airticket_orders(
    db: Session = Depends(deps.get_db),
    skip: int = 0,
    limit: int = 100,
    BookRecordName: Optional[str] = None,
    OrderStatus: Optional[str] = None,
    package_order_id: Optional[int] = None,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """获取机票订单列表"""
    try:
        query = db.query(AirticketOrder)
        
        # 根据用户角色和工作区过滤
        if current_user.role == "agent":
            # agent只能查看自己工作区的订单
            query = query.filter(AirticketOrder.work_area_id == current_user.workarea_id)
        elif current_user.role != "admin":
            # 非管理员且非agent的用户无权限查看
            raise HTTPException(
                status_code=403,
                detail="Not enough permissions to view airticket orders"
            )
        
        # 添加过滤条件，注意处理空字符串的情况
        if BookRecordName is not None and BookRecordName.strip():
            query = query.filter(AirticketOrder.BookRecordName.like(f"%{BookRecordName.strip()}%"))
            
        if OrderStatus is not None and OrderStatus.strip():
            query = query.filter(AirticketOrder.OrderStatus == OrderStatus.strip())
            
        # 按打包订单ID过滤
        if package_order_id is not None:
            if package_order_id <= 0:
                query = query.filter(AirticketOrder.package_order_id == -1)
            else:
                query = query.filter(AirticketOrder.package_order_id == package_order_id)
            
        # 添加排序和分页
        query = query.order_by(AirticketOrder.CreateTime.desc())
        orders = query.offset(skip).limit(limit).all()
        
        return orders
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"Error fetching airticket orders: {str(e)}"
        )

@router.post("/", response_model=schemas.AirticketOrder)
def create_airticket_order(
    *,
    db: Session = Depends(deps.get_db),
    order_in: schemas.AirticketOrderCreate,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """创建新的机票订单"""
    try:
        # 使用当前用户的工作区ID
        order_data = order_in.dict()
        order_data["work_area_id"] = current_user.workarea_id

        # 设置默认值
        if not order_data.get("package_order_id") or order_data["package_order_id"] <= 0:
            order_data["package_order_id"] = -1
            order_data["package_order_title"] = None
        else:
            # 如果关联了打包订单，查询订单标题
            package_order = db.query(PackageOrder).filter(
                PackageOrder.ID == order_data["package_order_id"]
            ).first()
            if package_order:
                order_data["package_order_title"] = package_order.title

        order = AirticketOrder(**order_data)
        db.add(order)
        db.commit()
        db.refresh(order)
        return order
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/{order_id}", response_model=schemas.AirticketOrder)
def get_airticket_order(
    order_id: int,
    db: Session = Depends(deps.get_db),
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """获取特定机票订单详情"""
    try:
        order = db.query(AirticketOrder).filter(AirticketOrder.ID == order_id).first()
        if not order:
            raise HTTPException(status_code=404, detail="Order not found")

        if current_user.role != "admin" and order.work_area_id != current_user.workarea_id:
            raise HTTPException(status_code=403, detail="Not enough permissions")

        return order
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.put("/{order_id}", response_model=schemas.AirticketOrder)
def update_airticket_order(
    *,
    db: Session = Depends(deps.get_db),
    order_id: int,
    order_in: schemas.AirticketOrderUpdate,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """更新机票订单信息"""
    try:
        order = db.query(AirticketOrder).filter(AirticketOrder.ID == order_id).first()
        if not order:
            raise HTTPException(status_code=404, detail="Order not found")

        # 检查权限
        if current_user.role != "admin" and order.work_area_id != current_user.workarea_id:
            raise HTTPException(status_code=403, detail="Not enough permissions")

        update_data = order_in.dict(exclude_unset=True)
        
        # 更新订单信息
        for field, value in update_data.items():
            setattr(order, field, value)

        db.add(order)
        db.commit()
        db.refresh(order)
        return order
    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e))

@router.delete("/{order_id}")
def delete_airticket_order(
    *,
    db: Session = Depends(deps.get_db),
    order_id: int,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """删除机票订单"""
    try:
        order = db.query(AirticketOrder).filter(AirticketOrder.ID == order_id).first()
        if not order:
            raise HTTPException(status_code=404, detail="Order not found")

        if current_user.role != "admin" and order.work_area_id != current_user.workarea_id:
            raise HTTPException(status_code=403, detail="Not enough permissions")

        db.delete(order)
        db.commit()
        return {"ok": True}
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e)) 